import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersistence from 'vuex-persist'
import cookies from 'js-cookie'
Vue.use(Vuex)



const state = {
    menuTree: [],
    paginationPageSizes: [5, 10, 15, 20],
    paginationLayout: "total, sizes, prev, pager, next, jumper",
    // 选择日期
    datePickerOptions: {
        shortcuts: [
            {
                text: "今天",
                onClick(picker) {
                    picker.$emit("pick", new Date());
                }
            },
            {
                text: "昨天",
                onClick(picker) {
                    const date = new Date();
                    date.setTime(date.getTime() - 3600 * 1000 * 24);
                    picker.$emit("pick", date);
                }
            },
            {
                text: "一周前",
                onClick(picker) {
                    const date = new Date();
                    date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit("pick", date);
                }
            }
        ]
    }
}

const getters = {
    token: state => state.user.token,
    role: state => state.user.role,
    name: state => state.user.name,
    permission_routes: state => state.permission.routes,
    menuTree: state => state.menuTree,
    paginationLayout: state => state.paginationLayout,
    datePickerOptions: state => state.datePickerOptions,
    paginationPageSizes: state => state.paginationPageSizes
}

const mutations = {
    setMenuTree(state, menuTree) {
        state.menuTree = menuTree
    }
}

const actions = {
    loadUserInfo({commit}, data) {
        // console.log("action loadUserInfo MenuTree:" + Object.entries(data ))
        commit('setMenuTree', data.menuTree)
    }
}

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
    // set './app.js' => 'app'
    const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
    const value = modulesFiles(modulePath)
    modules[moduleName] = value.default
    return modules
}, {})

const vuexLocal = new VuexPersistence({
    storage: window.localForge,
    // restoreState: (key, storage) => cookies.getJSON(key),
    // saveState: (key, state, storage) =>
    //     cookies.set(key, state, {
    //         expires: 3
    //     }),
})


const store = new Vuex.Store({
    state: state,
    getters: getters,
    mutations: mutations,
    actions: actions,
    modules: modules,
    plugins: [vuexLocal.plugin],
})

export default store
